/**
 * @AnimMrg.as
 *
 * @author sodaChen mail:sujun10#21cn.com
 * @version 1.0
 * <br>Copyright (C), 2013 asFrame.com
 * <br>This program is protected by copyright laws.
 * <br>Program Name:ASFrame
 * <br>Date:2016-6-5
 */
package com.asframe.mgr
{
	import com.asframe.collections.maps.HashMap;
	import com.asframe.pattern.Singleton;
	import com.asframe.tick.ITick;
	import com.asframe.utils.VectorUtils;

	import flash.display.Shape;
	import flash.events.Event;

	/**
	 * 动画管理器，必须实现tick接口，通过tick来播放（tick不等于游戏中的frameRate，是属于动画自己的频率）
	 * @author sodaChen
	 * Date:2016-6-5
	 */
	public class AnimMrg extends Singleton
	{
		private static var instance:AnimMrg;

		/** 舞台对象 **/
		public var frameRate:int = 30;
		/** 帧频率，1秒钟多少帧，默认是1秒钟10帧 **/
		private var sceFrameCount:int = 10;
		private var tickList:Vector.<ITick>;
		private var tickMap:HashMap;
		private var tickCount:int;
		private var tickMaxCount:int;
		private var tickLength:int;
		/** 心跳机制的动力机 **/
		private var power:Shape = new Shape();
		/**
		 * 获取实例的静态方法实例
		 * @return
		 *
		 */
		public static function getInstance():AnimMrg
		{
			if(instance == null)
			{
				instance = new AnimMrg();
			}
			return instance;
		}

		public function AnimMrg()
		{
			tickList = new Vector.<ITick>();
			tickMap = new HashMap();
			setSceFrameCount(sceFrameCount);
		}
		/**
		 * 设置1秒钟播放多少帧动画（通过设置找个值来改变速率）
		 * @param sceFrameCount
		 *
		 */
		public function setSceFrameCount(sceFrameCount:int):void
		{
			this.sceFrameCount = sceFrameCount;
			//更新计数器
			tickMaxCount = frameRate / sceFrameCount;
			tickCount = 0;
		}
		/**
		 * 添加动画
		 * @param tick
		 *
		 */
		public function addAnim(tick:ITick):void
		{
			if(tickMap.hasKey(tick))
				return ;
			tickMap.put(tick,tick);
			tickList.push(tick);
			tickLength = tickList.length;
		}
		/**
		 * 删除动画
		 * @param tick
		 *
		 */
		public function removeAnim(tick:ITick):void
		{
			tickMap.remove(tick);
			VectorUtils.removeItem(tickList,tick);
			tickLength = tickList.length;
		}
		/**
		 * 播放
		 *
		 */
		public function play():void
		{
			power.addEventListener(Event.ENTER_FRAME,onEnterFrame);
		}
		/**
		 * 停止
		 *
		 */
		public function stop():void
		{
			power.removeEventListener(Event.ENTER_FRAME,onEnterFrame);
		}
		private function onEnterFrame(evt:Event):void
		{
			tickCount++;
			if(tickCount >= tickMaxCount)
			{
				tickCount = 0;
				//避免在循环中会操作tickList找个数组
				var tempList:Vector.<ITick> = tickList.concat();
				var length:int = tempList.length;
				for (var i:int = 0; i < length; i++)
				{
					tempList[i].tick();
				}
			}
		}
	}
}